import {reactive} from "vue";
import axios from "axios";

// 描述用户的类型
export const UserType = {
    UNKNOWN: 0,
    ADMIN: 1,
    OPERATOR: 2,
    DRIVER: 3,
    properties: {
        1: {name: '管理员', url: '/admin'},
        2: {name: '操作员', url: '/operator'},
        3: {name: '司机', url: '/driver'},
    }
}

// 全局登录用户的存储状态
export const STORE = {
    userState: reactive({
        type: UserType.UNKNOWN,
        data: null
    })
}

export const logout = () => {
    STORE.userState.type = UserType.UNKNOWN;
    STORE.userState.data = null;
}

export const isLogin = () => STORE.userState.type != UserType.UNKNOWN

function saveAndCallback(result, userType, username, password, callback) {
    if (result) {
        STORE.userState.type = userType;
        STORE.userState.data = {
            username,
            password
        }
    }
    callback(result);
}

export const loginAccount = (userTypeName, username, password, callback) => {
    if (userTypeName === '管理员') {
        saveAndCallback(username === "admin" && password === "666",
            UserType.ADMIN, username, password, callback);
    } else if (userTypeName === '操作员') {
        axios({
            method: 'post', url: '/operator/login',
            params: {username, password}
        }).then((response) => {
            saveAndCallback(response.data, UserType.OPERATOR, username, password, callback);
        })
    } else if (userTypeName === '司机') {
        axios({
            method: 'post', url: '/driver/login',
            params: {username, password}
        }).then((response) => {
            saveAndCallback(response.data, UserType.DRIVER, username, password, callback);
        })
     }
}
